from django.db import models
from datetime import date  # 需要导入date模块


# 一、基础信息模块
class CityArea(models.Model):
    id = models.AutoField(primary_key=True, verbose_name="主键，自增")
    city_name = models.CharField(max_length=50, verbose_name="城市名称，如“深圳”")
    area_name = models.CharField(max_length=50, verbose_name="区域名称，如“南山区”")

    class Meta:
        verbose_name = "城市/区域表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.city_name}-{self.area_name}"


class User(models.Model):
    user_id = models.AutoField(primary_key=True, verbose_name="用户唯一标识")
    username = models.CharField(max_length=50, verbose_name="用户名/昵称")
    phone = models.CharField(max_length=20, unique=True, verbose_name="手机号，用于联系、登录")
    password = models.CharField(max_length=100, verbose_name="密码，或加密存储的凭证")
    identity_type = models.CharField(
        max_length=20,
        choices=[
            ("landlord", "房东"),  # 改为元组 (实际值, 显示名)
            ("tenant", "租客"),
            ("admin", "管理员")
        ],
        verbose_name="用户类型：房东/租客/管理员"
    )

    class Meta:
        verbose_name = "用户信息表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username


# 二、房源核心模块
class House(models.Model):
    house_id = models.AutoField(primary_key=True, verbose_name="房源主键")
    landlord_id = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="关联房东User.user_id")
    city_area_id = models.ForeignKey(CityArea, on_delete=models.CASCADE, verbose_name="关联CityArea.id")
    address = models.CharField(max_length=200, verbose_name="详细地址")
    house_type = models.CharField(max_length=50, verbose_name="户型，如“一室一厅”", blank=True, null=True)
    area_size = models.CharField(max_length=50, verbose_name="面积，如“50㎡”", blank=True, null=True)
    rent_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="每月租金", blank=True, null=True)
    deposit = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="押金", blank=True, null=True)
    facilities = models.TextField(verbose_name="配套设施，如“空调，热水器”", blank=True, null=True)
    status = models.CharField(
        max_length=20,
        choices=[
            ("vacant", "空房"),  # 改为元组
            ("rented", "已租")
        ],
        default="vacant",
        verbose_name="房源状态：空房/已租"
    )
    description = models.TextField(verbose_name="房源描述", blank=True, null=True,)
    images = models.TextField(verbose_name="房源图片路径，多图用逗号分隔", blank=True, null=True,)

    class Meta:
        verbose_name = "房源表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.address


# 三、租赁业务模块
class Contract(models.Model):
    contract_id = models.AutoField(primary_key=True, verbose_name="合同主键")
    house_id = models.ForeignKey(House, on_delete=models.CASCADE, verbose_name="关联房源House.house_id")
    tenant_id = models.ForeignKey(User, related_name="tenant_contracts", on_delete=models.CASCADE, verbose_name="关联租客User.user_id")
    landlord_id = models.ForeignKey(User, related_name="landlord_contracts", on_delete=models.CASCADE, verbose_name="关联房东User.user_id")
    start_date = models.DateField(verbose_name="起租日", blank=True, null=True, default=date.today) # 自动填充当前日期
    end_date = models.DateField(verbose_name="到期日")
    rent_cycle = models.CharField(max_length=50, verbose_name="租金周期，如“月付”")
    total_rent = models.DecimalField(max_digits=12, decimal_places=2, verbose_name="合同期总租金")
    status = models.CharField(
        max_length=20,
        choices=[
            ("valid", "有效"),  # 改为元组
            ("expired", "已到期"),
            ("terminated", "已解约")
        ],
        default="valid",
        verbose_name="合同状态：有效/已到期/已解约",
        blank=True,
        null=True
    )

    class Meta:
        verbose_name = "租赁合同表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"合同{self.contract_id}"


class RentBill(models.Model):
    bill_id = models.AutoField(primary_key=True, verbose_name="账单主键")
    contract_id = models.ForeignKey(Contract, on_delete=models.CASCADE, verbose_name="关联合同Contract.contract_id")
    bill_month = models.CharField(max_length=7, verbose_name="账单所属月份，如“2025-07”")
    rent_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="当月应收租金")
    paid_status = models.CharField(
        max_length=20,
        choices=[
            ("unpaid", "待收"),  # 改为元组
            ("paid", "已收")
        ],
        default="unpaid",
        verbose_name="支付状态：待收/已收",
        blank=True,
        null=True
    )
    paid_date = models.DateField(null=True, blank=True, verbose_name="支付日期")

    class Meta:
        verbose_name = "租金账单表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"账单{self.bill_id}（{self.bill_month}）"


# 四、辅助管理模块
class MeterReading(models.Model):
    reading_id = models.AutoField(primary_key=True, verbose_name="抄表记录主键")
    house_id = models.ForeignKey(House, on_delete=models.CASCADE, verbose_name="关联房源House.house_id")
    meter_type = models.CharField(
        max_length=20,
        choices=[
            ("electric", "电表"),  # 改为元组
            ("water", "水表")
        ],
        default="electric",
        verbose_name="表类型：电表/水表",
        blank=True,
        null=True

    )
    reading_date = models.DateField(verbose_name="抄表日期")
    previous_reading = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="上次读数")
    current_reading = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="本次读数")

    @property
    def consumption(self):
        """计算本期用量"""
        return self.current_reading - self.previous_reading

    class Meta:
        verbose_name = "抄表记录"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.get_meter_type_display()}抄表（{self.reading_date}）"


class Reminder(models.Model):
    reminder_id = models.AutoField(primary_key=True, verbose_name="提醒主键")
    related_id = models.IntegerField(verbose_name="关联业务ID")
    reminder_type = models.CharField(
        max_length=20,
        choices=[
            ("contract_expire", "合同到期"),  # 改为元组
            ("rent_unpaid", "租金待收")
        ],
        verbose_name="提醒类型"
    )
    reminder_content = models.CharField(max_length=500, verbose_name="提醒内容")
    remind_date = models.DateField(verbose_name="提醒触发日期")
    is_processed = models.CharField(
        max_length=20,
        choices=[
            ("no", "未处理"),  # 改为元组
            ("yes", "已处理")
        ],
        default="no",
        verbose_name="是否已处理",
        blank=True,
        null=True
    )

    class Meta:
        verbose_name = "提醒表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.reminder_content